package br.moneymonitor.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import br.moneymonitor.beans.User;

public class UserFactory extends DataBaseFactory {

	public static final String USER_TABLE = "user";

	public static final String ID = "_id";
	public static final String LOGIN = "login";
	public static final String PASSWORD = "password";
	public static final String USER_NAME = "userName";

	public static final String[] COLUMNS = { ID, LOGIN, PASSWORD, USER_NAME };

	public UserFactory(Context context) {
		super(context);
	}

	public long insert(User user) {
		ContentValues values = getContentValues(user);
		return super.insert(USER_TABLE, values);
	}

	public long salvar(User user) {
		long userId = user.getId();
		if (userId != 0) {
			return update(user);
		} else {
			return insert(user);
		}
	}

	private long update(User user) {
		ContentValues values = getContentValues(user);
		String userId = String.valueOf(user.getId());
		String[] whereArgs = new String[] { userId };
		return super.update(USER_TABLE, values, userId + "=?", whereArgs);
	}

	public int delete(User user) {
		String userId = String.valueOf(user.getId());
		String[] whereArgs = new String[] { userId };
		return db.delete(USER_TABLE, userId + "=?", whereArgs);
	}

	public User getUser(long id){
		Cursor c = super.select(USER_TABLE, COLUMNS, ID+"=?", new String[]{String.valueOf(id)});
		return getUser(c);
	}
	
	public User getUser(String login) {
		Cursor c = super.select(USER_TABLE, COLUMNS, LOGIN+"=?", new String[]{login});
		return getUser(c);
	}
	
	private User getUser(Cursor c){
		if(c != null && c.getCount() > 0){
			c.moveToFirst();
			User user = new User();
			user.setId(c.getLong(0));
			user.setLogin(c.getString(1));
			user.setPassword(c.getString(2));
			return user;
		}
		return null;
	}

	private ContentValues getContentValues(User user) {
		ContentValues values = new ContentValues();
		values.put(LOGIN, user.getLogin());
		values.put(PASSWORD, user.getPassword());
		values.put(USER_NAME, user.getUserName());
		return values;
	}


}
